package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
//import sun.security.util.ArrayUtil;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        List<Long> productIds = createOrderContext.getBuyProductIds();

        if (CollectionUtils.isEmpty(productIds)) {
            productIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
        }
        productIds.sort(Long::compareTo);

        List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        if (dtoList.size() != productIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        for (CartProductDto productDto : dtoList) {
            @NotNull @Min(0) Long productId = productDto.getProductId();
            Long productNum = productDto.getProductNum();

            Stock stock = stockMapper.selectStock(productId);
            Long stockCount = stock.getStockCount();
            Integer restrictCount = stock.getRestrictCount();

            if (stockCount < productNum) {
                throw new BizException(OrderRetCode.INSUFFICENT_INVENTORY.getCode(),
                        OrderRetCode.INSUFFICENT_INVENTORY.getMessage());
            }
            if (productNum > restrictCount) {
                throw new BizException(OrderRetCode.ORDEYBUY.getCode(),
                        OrderRetCode.ORDEYBUY.getMessage());
            }

            Stock stock1 = new Stock();
            stock1.setItemId(productId);
            stock1.setLockCount(productNum.intValue());
            stock1.setStockCount(-productNum);

            stockMapper.updateStock(stock1);
        }
        return true;
    }
}